<?php
/**
 * SKU功能测试脚本
 * 用于测试SKU数据的存储和检索功能
 */

require_once __DIR__ . '/vendor/autoload.php';

use app\model\GoodsModel;
use app\model\GoodsSpecModel;
use app\model\GoodsKuModel;

// 模拟测试数据
function testSkuFunctionality() {
    echo "开始测试SKU功能...\n";
    
    // 1. 测试创建商品
    echo "1. 创建测试商品...\n";
    $goods = new GoodsModel();
    $goods->title = '测试商品';
    $goods->image = '/test/image.jpg';
    $goods->sort_by = 100;
    $goods->status = 1;
    $goods->created_at = time();
    $goods->updated_at = time();
    $goods->save();
    
    $goodsId = $goods->id;
    echo "商品创建成功，ID: {$goodsId}\n";
    
    // 2. 测试创建规格
    echo "2. 创建商品规格...\n";
    $spec1 = new GoodsSpecModel();
    $spec1->goods_id = $goodsId;
    $spec1->spec_name = '颜色';
    $spec1->spec_value = '红色@蓝色@绿色';
    $spec1->save();
    
    $spec2 = new GoodsSpecModel();
    $spec2->goods_id = $goodsId;
    $spec2->spec_name = '尺寸';
    $spec2->spec_value = 'S@M@L@XL';
    $spec2->save();
    
    echo "规格创建成功\n";
    
    // 3. 测试保存SKU数据
    echo "3. 保存SKU数据...\n";
    $skuData = [
        [
            'specs' => '红色@S',
            'price' => 99.00,
            'v' => 10
        ],
        [
            'specs' => '红色@M',
            'price' => 99.00,
            'v' => 15
        ],
        [
            'specs' => '蓝色@L',
            'price' => 109.00,
            'v' => 8
        ],
        [
            'specs' => '绿色@XL',
            'price' => 119.00,
            'v' => 5
        ]
    ];
    
    $result = GoodsKuModel::batchSave($goodsId, $skuData);
    echo "SKU保存结果: " . ($result ? '成功' : '失败') . "\n";
    
    // 4. 测试查询SKU
    echo "4. 查询SKU数据...\n";
    $skuList = GoodsKuModel::getByGoodsId($goodsId);
    echo "找到 " . count($skuList) . " 个SKU:\n";
    foreach ($skuList as $sku) {
        echo "  - 规格: {$sku->specs}, 价格: {$sku->price}, 库存: {$sku->v}\n";
    }
    
    // 5. 测试根据规格组合查询
    echo "5. 根据规格组合查询SKU...\n";
    $testSpecs = '红色@S';
    $sku = GoodsKuModel::findBySpecs($goodsId, $testSpecs);
    if ($sku) {
        echo "找到规格组合 '{$testSpecs}' 的SKU: 价格 {$sku->price}, 库存 {$sku->v}\n";
    } else {
        echo "未找到规格组合 '{$testSpecs}' 的SKU\n";
    }
    
    // 6. 清理测试数据
    echo "6. 清理测试数据...\n";
    GoodsKuModel::where('goods_id', $goodsId)->delete();
    GoodsSpecModel::where('goods_id', $goodsId)->delete();
    $goods->delete();
    
    echo "测试完成！\n";
}

// 运行测试
try {
    testSkuFunctionality();
} catch (Exception $e) {
    echo "测试失败: " . $e->getMessage() . "\n";
    echo "错误位置: " . $e->getFile() . ":" . $e->getLine() . "\n";
} 